<!DOCTYPE html><html lang="en" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0"><title>手写 Spring | 戴涛的宝藏</title><meta name="author" content="戴涛"><meta name="copyright" content="戴涛"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="IOC执行原理总流程：解析config配置类，得到扫描路径包，解析包下的所有目标类，得到BeanDefinitions，动态创建bean实例对象，最终生成ioc容器。所以我们可以把这个流程分为：  解析config配置类 扫描路径包 解析所有目标类 得到所有BeanDefinition 创建bean实例对象 生成ioc容器   前期准备工作：编写注解@ComponentScan思想：根据注解获取扫">
<meta property="og:type" content="article">
<meta property="og:title" content="手写 Spring">
<meta property="og:url" content="https://declan1.gitee.io/2023/03/17/%E6%89%8B%E5%86%99-Spring/index.html">
<meta property="og:site_name" content="戴涛的宝藏">
<meta property="og:description" content="IOC执行原理总流程：解析config配置类，得到扫描路径包，解析包下的所有目标类，得到BeanDefinitions，动态创建bean实例对象，最终生成ioc容器。所以我们可以把这个流程分为：  解析config配置类 扫描路径包 解析所有目标类 得到所有BeanDefinition 创建bean实例对象 生成ioc容器   前期准备工作：编写注解@ComponentScan思想：根据注解获取扫">
<meta property="og:locale" content="en_US">
<meta property="og:image" content="https://img.lovetao.top/img/202303152100335.jpg">
<meta property="article:published_time" content="2023-03-16T16:09:00.000Z">
<meta property="article:modified_time" content="2023-03-16T16:09:27.904Z">
<meta property="article:author" content="戴涛">
<meta property="article:tag" content="Spring">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://img.lovetao.top/img/202303152100335.jpg"><link rel="shortcut icon" href="/img/favicon.png"><link rel="canonical" href="https://declan1.gitee.io/2023/03/17/%E6%89%8B%E5%86%99-Spring/index.html"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: undefined,
  translate: undefined,
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: 'Copy successfully',
    error: 'Copy error',
    noSupport: 'The browser does not support'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '',
  date_suffix: {
    just: 'Just',
    min: 'minutes ago',
    hour: 'hours ago',
    day: 'days ago',
    month: 'months ago'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: false,
  isAnchor: false,
  percent: {
    toc: true,
    rightside: false,
  }
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: '手写 Spring',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2023-03-17 00:09:27'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
    win.getCSS = (url,id = false) => new Promise((resolve, reject) => {
      const link = document.createElement('link')
      link.rel = 'stylesheet'
      link.href = url
      if (id) link.id = id
      link.onerror = reject
      link.onload = link.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        link.onload = link.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(link)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><meta name="generator" content="Hexo 6.3.0"></head><body><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src="https://img.lovetao.top/img/202303152100335.jpg" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/archives/"><div class="headline">Articles</div><div class="length-num">61</div></a><a href="/tags/"><div class="headline">Tags</div><div class="length-num">9</div></a><a href="/categories/"><div class="headline">Categories</div><div class="length-num">9</div></a></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/messageboard/"><i class="fa-fw fas fa-tags"></i><span> 留言板</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 链接</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('https://img.lovetao.top/img/202303152113310.jpg')"><nav id="nav"><span id="blog-info"><a href="/" title="戴涛的宝藏"><span class="site-name">戴涛的宝藏</span></a></span><div id="menus"><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/messageboard/"><i class="fa-fw fas fa-tags"></i><span> 留言板</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 链接</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div><div id="toggle-menu"><a class="site-page" href="javascript:void(0);"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">手写 Spring</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">Created</span><time class="post-meta-date-created" datetime="2023-03-16T16:09:00.000Z" title="Created 2023-03-17 00:09:00">2023-03-17</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">Updated</span><time class="post-meta-date-updated" datetime="2023-03-16T16:09:27.904Z" title="Updated 2023-03-17 00:09:27">2023-03-17</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/Spring/">Spring</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="手写 Spring"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">Post View:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h2 id="IOC执行原理"><a href="#IOC执行原理" class="headerlink" title="IOC执行原理"></a>IOC执行原理</h2><p><strong>总流程</strong>：解析config配置类，得到扫描路径包，解析包下的所有目标类，得到BeanDefinitions，动态创建bean实例对象，最终生成ioc容器。<br>所以我们可以把这个流程分为：</p>
<ul>
<li>解析config配置类</li>
<li>扫描路径包</li>
<li>解析所有目标类</li>
<li>得到所有BeanDefinition</li>
<li>创建bean实例对象</li>
<li>生成ioc容器</li>
</ul>
<p><img src="http://jxau7124.oss-cn-shenzhen.aliyuncs.com/images/20230317_0003505637.png" alt="image.png"></p>
<h2 id="前期准备工作：编写注解"><a href="#前期准备工作：编写注解" class="headerlink" title="前期准备工作：编写注解"></a>前期准备工作：编写注解</h2><p><strong>@ComponentScan</strong><br>思想：根据注解获取扫描路径&#x3D;&#x3D;&gt;框架开始扫描，new出实例放入到容器中<br><img src="http://jxau7124.oss-cn-shenzhen.aliyuncs.com/images/20230317_0003529190.png" alt="image.png"></p>
<p><strong>@Component</strong><br><img src="http://jxau7124.oss-cn-shenzhen.aliyuncs.com/images/20230317_0003527540.png" alt="image.png"></p>
<h2 id="步骤一：解析配置类"><a href="#步骤一：解析配置类" class="headerlink" title="步骤一：解析配置类"></a>步骤一：解析配置类</h2><p><strong>主要流程：</strong>获取配置类上的注解–》获取包扫描路径–》获取目标文件夹资源</p>
<ul>
<li>获取配置类上的注解，得到扫描路径</li>
</ul>
<p><img src="http://jxau7124.oss-cn-shenzhen.aliyuncs.com/images/20230317_0003544628.png" alt="image.png"></p>
<ul>
<li>在得到路径后，我们使用类加载器进行加载资源，这里使用appClassloader。通过类加载器加载路径，这里的参数为文件夹相对路径，最后得到目标目录资源。</li>
</ul>
<p><img src="http://jxau7124.oss-cn-shenzhen.aliyuncs.com/images/20230317_0003553685.png" alt="image.png"></p>
<h2 id="第二步：加载所有目标类"><a href="#第二步：加载所有目标类" class="headerlink" title="第二步：加载所有目标类"></a>第二步：加载所有目标类</h2><p>这里的目标类指的是，目标文件下所有带有@Component注解的.class结尾的类文件。</p>
<ul>
<li>找到全限定类名，然后通过类加载器得到对应的类对象</li>
</ul>
<p><img src="http://jxau7124.oss-cn-shenzhen.aliyuncs.com/images/20230317_0003573885.png" alt="image.png"></p>
<ul>
<li>通过反射，得到类的注解。</li>
<li>判断是单例bean还是原型bean；判断有没有@Scope注解，有的话就是单例Bean。</li>
<li>生成BeanDefination对象</li>
</ul>
<p><img src="http://jxau7124.oss-cn-shenzhen.aliyuncs.com/images/20230317_0003584817.png" alt="image.png"></p>
<ul>
<li>把生成的BeanDifinition对象放入容器中</li>
</ul>
<p><img src="http://jxau7124.oss-cn-shenzhen.aliyuncs.com/images/20230317_0004004676.png" alt="image.png"></p>
<h3 id="说明："><a href="#说明：" class="headerlink" title="说明："></a>说明：</h3><h4 id="单例Bean和原型Bean"><a href="#单例Bean和原型Bean" class="headerlink" title="单例Bean和原型Bean"></a>单例Bean和原型Bean</h4><p>在加载玩所有目标类时，需要创建单例bean放入单例池中；在以后getBean时直接从单例池中获取。<br>如果是原型bean时，getBean方法中，会根据这个原型bean的beanDifition创建一个对象。<br><img src="http://jxau7124.oss-cn-shenzhen.aliyuncs.com/images/20230317_0004018890.png" alt="image.png"><br><code>protorype</code>表示原型；<code>singleton</code>表示单例</p>
<h4 id="BeanDefination"><a href="#BeanDefination" class="headerlink" title="BeanDefination"></a>BeanDefination</h4><p>为什么要有：在getBean时，需要通过传进来的类名参数去获取这个类的具体信息（单例bean或者原型bean）;	是一个找到类并且解析类的一个过程（涉及到重复执行）；所以可以在刚开始扫描的时候就对其进行解析并保存</p>
<p><img src="http://jxau7124.oss-cn-shenzhen.aliyuncs.com/images/20230317_0004028594.png" alt="image.png"></p>
<h2 id="第三步：循环解析beanDefinitionMap"><a href="#第三步：循环解析beanDefinitionMap" class="headerlink" title="第三步：循环解析beanDefinitionMap"></a>第三步：循环解析beanDefinitionMap</h2><p><strong>思路：</strong>循环map中所有的beandifinition，依次判断其scope属性，如果是单例bean,直接根据的beandifination然后creatBean()放进单例池中</p>
<p><img src="http://jxau7124.oss-cn-shenzhen.aliyuncs.com/images/20230317_0004033524.png" alt="image.png"></p>
<h2 id="第四步：创建bean实例对象"><a href="#第四步：创建bean实例对象" class="headerlink" title="第四步：创建bean实例对象"></a>第四步：创建bean实例对象</h2><p><strong>思路：</strong>这里创建bean实例主要根据bean的定义信息beanDifintion创建。根据beandifition中的class属性，new出实例<br><img src="http://jxau7124.oss-cn-shenzhen.aliyuncs.com/images/20230317_0004043891.png" alt="image.png"></p>
<h3 id="依赖注入"><a href="#依赖注入" class="headerlink" title="依赖注入"></a>依赖注入</h3><p>功能描述：通过需要依赖注入的属性名字（ByName）或者类型(ByType)在ioc容器中找到对应的beandefinition信息<br><img src="http://jxau7124.oss-cn-shenzhen.aliyuncs.com/images/20230317_0004051448.png" alt="image.png"></p>
<p><strong>思路：</strong>遍历该类的每一个属性字段，发现需要注入的字段（带有Autowired注解），从ioc容器中拿出对象进行反射赋值操作<br><img src="http://jxau7124.oss-cn-shenzhen.aliyuncs.com/images/20230317_0004074877.png" alt="image.png"><br>说明：</p>
<ul>
<li><strong>getDeclaredFields()方法</strong>用于返回一个Field对象数组，<strong>该数组指示所有Field</strong>(即它是私有，公共，受保护还是默认)，但不包括继承的字段。</li>
<li><strong>getFields()方法</strong>用于返回一个Field对象数组，这些对象指示此Class对象表示的类或接口的所有<strong>公共Field。</strong></li>
</ul>
<p><strong>问题：</strong><br>1、创建userservice的时候，还没有orderservice，get不到怎么办<br>2、如果在对一个bean进行依赖注入的时候，注入的bean不存在，注入的就为空<br>3、这样的写法会让原型bean注入单例bean失败<br>4、如果orderservice中注入userservice就有问题了，第一次createBean的时候根本get不到userService<br>5、在两个类都为单例bean时，OrderService里有UserService，并且OrderService先解析，会出现问题<br><strong>解决：</strong><br>1、所以应该在getbean这个方法时就要进行判断，该bean不存在就立刻创建，根据我们的beanDefinitionMap创建出来<br><strong>解决之后出现的问题：</strong><br>1、 出现循环依赖问题，即：外层给内层赋值时，内层需要创建实例，但是内层对象里有外层属性；<br>2、目前想到的解决措施：先判断内层里有没有外层（递归），有的话只创建内层，内层属性后面再注入</p>
<h2 id="第五步：获取Bean对象"><a href="#第五步：获取Bean对象" class="headerlink" title="第五步：获取Bean对象"></a>第五步：获取Bean对象</h2><h3 id="GetBean（）"><a href="#GetBean（）" class="headerlink" title="GetBean（）"></a>GetBean（）</h3><p><strong>思路：</strong>判断类名是否在Ioc容器中(beandifinitionMap)，不在的话抛出异常，如果在的话，判断是否是单例bean,如果是的话就从单例池中取出，不是的话就根据beandifnition创建bean返回（原型的作用）。<br><img src="http://jxau7124.oss-cn-shenzhen.aliyuncs.com/images/20230317_0004108456.png" alt="image.png"></p>
<h2 id="回顾基础知识"><a href="#回顾基础知识" class="headerlink" title="回顾基础知识"></a>回顾基础知识</h2><h3 id="1、三种类加载器以及加载的文件"><a href="#1、三种类加载器以及加载的文件" class="headerlink" title="1、三种类加载器以及加载的文件"></a>1、三种类加载器以及加载的文件</h3><p><img src="http://jxau7124.oss-cn-shenzhen.aliyuncs.com/images/20230317_0004132629.png" alt="image.png"></p>
<h3 id="2、getDeclaredAnnotation-方法：得到类上的注解"><a href="#2、getDeclaredAnnotation-方法：得到类上的注解" class="headerlink" title="2、getDeclaredAnnotation()方法：得到类上的注解"></a>2、getDeclaredAnnotation()方法：得到类上的注解</h3><h3 id="3、通过全限定类名加载类"><a href="#3、通过全限定类名加载类" class="headerlink" title="3、通过全限定类名加载类"></a>3、通过全限定类名加载类</h3><p><img src="http://jxau7124.oss-cn-shenzhen.aliyuncs.com/images/20230317_0004145108.png" alt="image.png"></p>
<p>具体代码：<br><img src="http://jxau7124.oss-cn-shenzhen.aliyuncs.com/images/20230317_0004142322.png" alt="image.png"></p>
<h2 id="Spring提供的扩展接口"><a href="#Spring提供的扩展接口" class="headerlink" title="Spring提供的扩展接口"></a>Spring提供的扩展接口</h2><h3 id="BeanNameAaware"><a href="#BeanNameAaware" class="headerlink" title="BeanNameAaware"></a>BeanNameAaware</h3><p>功能：Aware回调	<br>流程：创建一个BeanNameAware接口，然后规定行为，进行回调<br>再创建bean时，依赖注入后，判断你这个类是不是beanNameAware(或者实现了这个接口)<br><img src="http://jxau7124.oss-cn-shenzhen.aliyuncs.com/images/20230317_0004156375.png" alt="image.png"></p>
<h3 id="InitializingBean初始化"><a href="#InitializingBean初始化" class="headerlink" title="InitializingBean初始化"></a>InitializingBean初始化</h3><p><img src="http://jxau7124.oss-cn-shenzhen.aliyuncs.com/images/20230317_0004162926.png" alt="image.png"><br><strong>功能：</strong>初始化时做某些功能<br><strong>用途：</strong><br>1、初始化时就从数据库查询信息赋值给相应的对象<br>3、验证某一个属性是否为空<br>2、第三方框架整合<br><img src="http://jxau7124.oss-cn-shenzhen.aliyuncs.com/images/20230317_0004174203.png" alt="image.png"></p>
<h3 id="BeanPostProcessor"><a href="#BeanPostProcessor" class="headerlink" title="BeanPostProcessor"></a>BeanPostProcessor</h3><p>功能：spring提供的扩展接口，在bean创建前创建<br><img src="http://jxau7124.oss-cn-shenzhen.aliyuncs.com/images/20230317_0004183817.png" alt="image.png"></p>
<p>写一个实现类，去实现这两个方法，实现类要带上@Component放入容器中<br><img src="http://jxau7124.oss-cn-shenzhen.aliyuncs.com/images/20230317_0004199880.png" alt="image.png"></p>
<p>在扫描的时候，判断class是否实现了这个接口<br><img src="http://jxau7124.oss-cn-shenzhen.aliyuncs.com/images/20230317_0004207485.png" alt="image.png"><br>创建bean实例后，直接放入集合中<br><img src="http://jxau7124.oss-cn-shenzhen.aliyuncs.com/images/20230317_0004202330.png" alt="image.png"><br><strong>思考：在配置类时，也可以通过加注解的方式，把自己相加的扩展接口放入容器中</strong></p>
<p>在初始化之前执行这个方法<br><img src="http://jxau7124.oss-cn-shenzhen.aliyuncs.com/images/20230317_0004211185.png" alt="image.png"></p>
<h4 id="AOP动态代理"><a href="#AOP动态代理" class="headerlink" title="AOP动态代理"></a>AOP动态代理</h4><p><img src="http://jxau7124.oss-cn-shenzhen.aliyuncs.com/images/20230317_0004225850.png" alt="image.png"></p>
<p>扩展，根据<strong>切点</strong>进一步明确需求</p>
<h2 id="Bean的生命周期"><a href="#Bean的生命周期" class="headerlink" title="Bean的生命周期"></a>Bean的生命周期</h2><p>创建的生命周期：<br>实例化（根据BeanDefinition进行创建）–》对象–》属性填充（依赖注入）–》初始化（InitializingBean）–》Aop–&gt;代理对象–》Bean对象	<br><img src="http://jxau7124.oss-cn-shenzhen.aliyuncs.com/images/20230317_0004233570.png" alt="image.png"></p>
<p>注意：不要把JVM的初始化和Spring的初始化搞混了；实例化得到对象，初始化执行方法；</p>
<h4 id="源码解析"><a href="#源码解析" class="headerlink" title="源码解析"></a>源码解析</h4><blockquote>
<p>_&#x2F;**</p>
</blockquote>
<ul>
<li>Central method of this class: creates a bean instance,</li>
<li>populates the bean instance, applies post-processors, etc.</li>
<li><em>**</em>@see <em>**</em>#doCreateBean<br>*&#x2F;_</li>
</ul>
<blockquote>
<p>protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)<br>_翻译：_这个类的中心方法:创建一个bean实例，填充这个bean实例，应用后处理器，等等。</p>
</blockquote>
<p>最核心的方法：<strong>doCreateBean()</strong><br><img src="http://jxau7124.oss-cn-shenzhen.aliyuncs.com/images/20230317_0004247699.png" alt="image.png"></p>
<p>判断类是否实现了那个接口，实现了就调用前置处理，如果没实现的话直接进行初始化（afterPropertiesSet（））</p>
<p><img src="http://jxau7124.oss-cn-shenzhen.aliyuncs.com/images/20230317_0004288244.png" alt="image.png"></p>
<p><img src="http://jxau7124.oss-cn-shenzhen.aliyuncs.com/images/20230317_0004305780.png" alt="image.png"></p>
<p><img src="http://jxau7124.oss-cn-shenzhen.aliyuncs.com/images/20230317_0004312493.png" alt="image.png"></p>
<p><img src="http://jxau7124.oss-cn-shenzhen.aliyuncs.com/images/20230317_0004328903.png" alt="image.png"></p>
<p><strong>逻辑：</strong>查看你是否实现了InitializingBean接口，实现了就调用方法<br><img src="http://jxau7124.oss-cn-shenzhen.aliyuncs.com/images/20230317_0004338707.png" alt="image.png"></p>
<p><img src="http://jxau7124.oss-cn-shenzhen.aliyuncs.com/images/20230317_0004353626.png" alt="image.png"></p>
<p>处理Aop两个步骤：<br>1、缓存所有的切面bean	<br>2、当前类是切面，并且有匹配的切点<br><img src="http://jxau7124.oss-cn-shenzhen.aliyuncs.com/images/20230317_0004369886.png" alt="image.png"></p>
<h4 id="动态代理"><a href="#动态代理" class="headerlink" title="动态代理"></a>动态代理</h4><p><strong>被代理对象（target）有属性，根据流程走的代理对象没有属性</strong><br><strong>流程：</strong><br><img src="http://jxau7124.oss-cn-shenzhen.aliyuncs.com/images/20230317_0004377791.png" alt="image.png"></p>
<p>CGLIB对象动态代理流程<br><img src="http://jxau7124.oss-cn-shenzhen.aliyuncs.com/images/20230317_0004375191.png" alt="image.png"></p>
<p><strong>DeBug过程</strong><br><img src="http://jxau7124.oss-cn-shenzhen.aliyuncs.com/images/20230317_0004384563.png" alt="image.png"></p>
<h4 id="默认构造方法"><a href="#默认构造方法" class="headerlink" title="默认构造方法"></a>默认构造方法</h4><p><img src="http://jxau7124.oss-cn-shenzhen.aliyuncs.com/images/20230317_0004398960.png" alt="image.png"></p>
<h4 id="byName-x2F-byType"><a href="#byName-x2F-byType" class="headerlink" title="byName&#x2F;byType"></a>byName&#x2F;byType</h4><p>byName缺点：<br>1、根据名字获得的bean对象，获得后与参数类型不一致<br>做法：<br>先是byType然后再是byName，如果通过type找到了多个bean，然后参数名字对应不上，出现报错<br><img src="http://jxau7124.oss-cn-shenzhen.aliyuncs.com/images/20230317_0004401132.png" alt="image.png"></p>
<h2 id="Spring事务"><a href="#Spring事务" class="headerlink" title="Spring事务"></a>Spring事务</h2><h4 id="配置这个才代表事务生效"><a href="#配置这个才代表事务生效" class="headerlink" title="配置这个才代表事务生效"></a>配置这个才代表事务生效</h4><p><img src="http://jxau7124.oss-cn-shenzhen.aliyuncs.com/images/20230317_0004419314.png" alt="image.png"></p>
<p>代理对象去调用才有用<br><img src="http://jxau7124.oss-cn-shenzhen.aliyuncs.com/images/20230317_0004422015.png" alt="image.png"></p>
<p>解决方式：自己注入自己<br>这个是从容器中获取对象，根据流程走，放入容器中的最后是代理对象<br><img src="http://jxau7124.oss-cn-shenzhen.aliyuncs.com/images/20230317_0004425040.png" alt="image.png"><br>然后使用代理对象去调用<br><img src="http://jxau7124.oss-cn-shenzhen.aliyuncs.com/images/20230317_0004439113.png" alt="image.png"></p>
<p>情况2：<br>事务依旧失效<br><img src="http://jxau7124.oss-cn-shenzhen.aliyuncs.com/images/20230317_0004442960.png" alt="image.png"></p>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">Author: </span><span class="post-copyright-info"><a href="https://declan1.gitee.io">戴涛</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">Link: </span><span class="post-copyright-info"><a href="https://declan1.gitee.io/2023/03/17/%E6%89%8B%E5%86%99-Spring/">https://declan1.gitee.io/2023/03/17/%E6%89%8B%E5%86%99-Spring/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">Copyright Notice: </span><span class="post-copyright-info">All articles in this blog are licensed under <a target="_blank" rel="noopener" href="https://creativecommons.org/licenses/by-nc-sa/4.0/">CC BY-NC-SA 4.0</a> unless stating additionally.</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/Spring/">Spring</a></div><div class="post_share"><div class="social-share" data-image="https://img.lovetao.top/img/202303152100335.jpg" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/2023/03/17/MySQL-%E4%B8%AD%E7%9A%84%E9%94%81/" title="MySQL 中的锁"><div class="cover" style="background: var(--default-bg-color)"></div><div class="pagination-info"><div class="label">Previous Post</div><div class="prev_info">MySQL 中的锁</div></div></a></div><div class="next-post pull-right"><a href="/2023/03/17/Redis-%E4%B8%BB%E4%BB%8E%E6%9E%B6%E6%9E%84/" title="Redis 主从架构"><div class="cover" style="background: var(--default-bg-color)"></div><div class="pagination-info"><div class="label">Next Post</div><div class="next_info">Redis 主从架构</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span>Related Articles</span></div><div class="relatedPosts-list"><div><a href="/2023/03/15/Spring-AOP/" title="Spring AOP"><div class="cover" style="background: var(--default-bg-color)"></div><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-03-15</div><div class="title">Spring AOP</div></div></a></div><div><a href="/2023/03/22/Spring-%E4%BA%8B%E5%8A%A1/" title="Spring 事务"><div class="cover" style="background: var(--default-bg-color)"></div><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-03-22</div><div class="title">Spring 事务</div></div></a></div><div><a href="/2023/03/22/Spring-%E5%BE%AA%E7%8E%AF%E4%BE%9D%E8%B5%96/" title="Spring 循环依赖"><div class="cover" style="background: var(--default-bg-color)"></div><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-03-22</div><div class="title">Spring 循环依赖</div></div></a></div><div><a href="/2023/03/23/Spring-%E4%BA%8B%E5%8A%A1%E4%BC%A0%E6%92%AD%E6%9C%BA%E5%88%B6/" title="Spring 事务传播机制"><div class="cover" style="background: var(--default-bg-color)"></div><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-03-23</div><div class="title">Spring 事务传播机制</div></div></a></div><div><a href="/2023/03/22/Spring-%E7%9F%A5%E8%AF%86%E7%82%B9/" title="Spring 知识点"><div class="cover" style="background: var(--default-bg-color)"></div><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-03-22</div><div class="title">Spring 知识点</div></div></a></div><div><a href="/2023/03/22/bean%E5%AF%B9%E8%B1%A1%E7%9A%84%E5%88%9B%E5%BB%BA%E8%BF%87%E7%A8%8B/" title="bean对象的创建过程"><div class="cover" style="background: var(--default-bg-color)"></div><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-03-22</div><div class="title">bean对象的创建过程</div></div></a></div></div></div><hr/><div id="post-comment"><div class="comment-head"><div class="comment-headline"><i class="fas fa-comments fa-fw"></i><span> Comment</span></div></div><div class="comment-wrap"><div><div class="vcomment" id="vcomment"></div></div></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src="https://img.lovetao.top/img/202303152100335.jpg" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">戴涛</div><div class="author-info__description">虽平凡，但不甘于平凡</div></div><div class="card-info-data site-data is-center"><a href="/archives/"><div class="headline">Articles</div><div class="length-num">61</div></a><a href="/tags/"><div class="headline">Tags</div><div class="length-num">9</div></a><a href="/categories/"><div class="headline">Categories</div><div class="length-num">9</div></a></div><a id="card-info-btn" target="_blank" rel="noopener" href="https://github.com/xxxxxx"><i class="fab fa-github"></i><span>Follow Me</span></a><div class="card-info-social-icons is-center"><a class="social-icon" href="https://gitee.com/declan1" target="_blank" title="Github"><i class="fab fa-github"></i></a><a class="social-icon" href="mailto:coder_tao@163.com" target="_blank" title="Email"><i class="fas fa-envelope"></i></a></div></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn fa-shake"></i><span>Announcement</span></div><div class="announcement_content">This is my Blog</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>Catalog</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#IOC%E6%89%A7%E8%A1%8C%E5%8E%9F%E7%90%86"><span class="toc-number">1.</span> <span class="toc-text">IOC执行原理</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%89%8D%E6%9C%9F%E5%87%86%E5%A4%87%E5%B7%A5%E4%BD%9C%EF%BC%9A%E7%BC%96%E5%86%99%E6%B3%A8%E8%A7%A3"><span class="toc-number">2.</span> <span class="toc-text">前期准备工作：编写注解</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%AD%A5%E9%AA%A4%E4%B8%80%EF%BC%9A%E8%A7%A3%E6%9E%90%E9%85%8D%E7%BD%AE%E7%B1%BB"><span class="toc-number">3.</span> <span class="toc-text">步骤一：解析配置类</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%AC%AC%E4%BA%8C%E6%AD%A5%EF%BC%9A%E5%8A%A0%E8%BD%BD%E6%89%80%E6%9C%89%E7%9B%AE%E6%A0%87%E7%B1%BB"><span class="toc-number">4.</span> <span class="toc-text">第二步：加载所有目标类</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E8%AF%B4%E6%98%8E%EF%BC%9A"><span class="toc-number">4.1.</span> <span class="toc-text">说明：</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%8D%95%E4%BE%8BBean%E5%92%8C%E5%8E%9F%E5%9E%8BBean"><span class="toc-number">4.1.1.</span> <span class="toc-text">单例Bean和原型Bean</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#BeanDefination"><span class="toc-number">4.1.2.</span> <span class="toc-text">BeanDefination</span></a></li></ol></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%AC%AC%E4%B8%89%E6%AD%A5%EF%BC%9A%E5%BE%AA%E7%8E%AF%E8%A7%A3%E6%9E%90beanDefinitionMap"><span class="toc-number">5.</span> <span class="toc-text">第三步：循环解析beanDefinitionMap</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%AC%AC%E5%9B%9B%E6%AD%A5%EF%BC%9A%E5%88%9B%E5%BB%BAbean%E5%AE%9E%E4%BE%8B%E5%AF%B9%E8%B1%A1"><span class="toc-number">6.</span> <span class="toc-text">第四步：创建bean实例对象</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BE%9D%E8%B5%96%E6%B3%A8%E5%85%A5"><span class="toc-number">6.1.</span> <span class="toc-text">依赖注入</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%AC%AC%E4%BA%94%E6%AD%A5%EF%BC%9A%E8%8E%B7%E5%8F%96Bean%E5%AF%B9%E8%B1%A1"><span class="toc-number">7.</span> <span class="toc-text">第五步：获取Bean对象</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#GetBean%EF%BC%88%EF%BC%89"><span class="toc-number">7.1.</span> <span class="toc-text">GetBean（）</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%9B%9E%E9%A1%BE%E5%9F%BA%E7%A1%80%E7%9F%A5%E8%AF%86"><span class="toc-number">8.</span> <span class="toc-text">回顾基础知识</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#1%E3%80%81%E4%B8%89%E7%A7%8D%E7%B1%BB%E5%8A%A0%E8%BD%BD%E5%99%A8%E4%BB%A5%E5%8F%8A%E5%8A%A0%E8%BD%BD%E7%9A%84%E6%96%87%E4%BB%B6"><span class="toc-number">8.1.</span> <span class="toc-text">1、三种类加载器以及加载的文件</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2%E3%80%81getDeclaredAnnotation-%E6%96%B9%E6%B3%95%EF%BC%9A%E5%BE%97%E5%88%B0%E7%B1%BB%E4%B8%8A%E7%9A%84%E6%B3%A8%E8%A7%A3"><span class="toc-number">8.2.</span> <span class="toc-text">2、getDeclaredAnnotation()方法：得到类上的注解</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3%E3%80%81%E9%80%9A%E8%BF%87%E5%85%A8%E9%99%90%E5%AE%9A%E7%B1%BB%E5%90%8D%E5%8A%A0%E8%BD%BD%E7%B1%BB"><span class="toc-number">8.3.</span> <span class="toc-text">3、通过全限定类名加载类</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Spring%E6%8F%90%E4%BE%9B%E7%9A%84%E6%89%A9%E5%B1%95%E6%8E%A5%E5%8F%A3"><span class="toc-number">9.</span> <span class="toc-text">Spring提供的扩展接口</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#BeanNameAaware"><span class="toc-number">9.1.</span> <span class="toc-text">BeanNameAaware</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#InitializingBean%E5%88%9D%E5%A7%8B%E5%8C%96"><span class="toc-number">9.2.</span> <span class="toc-text">InitializingBean初始化</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#BeanPostProcessor"><span class="toc-number">9.3.</span> <span class="toc-text">BeanPostProcessor</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#AOP%E5%8A%A8%E6%80%81%E4%BB%A3%E7%90%86"><span class="toc-number">9.3.1.</span> <span class="toc-text">AOP动态代理</span></a></li></ol></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Bean%E7%9A%84%E7%94%9F%E5%91%BD%E5%91%A8%E6%9C%9F"><span class="toc-number">10.</span> <span class="toc-text">Bean的生命周期</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%BA%90%E7%A0%81%E8%A7%A3%E6%9E%90"><span class="toc-number">10.0.1.</span> <span class="toc-text">源码解析</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%8A%A8%E6%80%81%E4%BB%A3%E7%90%86"><span class="toc-number">10.0.2.</span> <span class="toc-text">动态代理</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E9%BB%98%E8%AE%A4%E6%9E%84%E9%80%A0%E6%96%B9%E6%B3%95"><span class="toc-number">10.0.3.</span> <span class="toc-text">默认构造方法</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#byName-x2F-byType"><span class="toc-number">10.0.4.</span> <span class="toc-text">byName&#x2F;byType</span></a></li></ol></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Spring%E4%BA%8B%E5%8A%A1"><span class="toc-number">11.</span> <span class="toc-text">Spring事务</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E9%85%8D%E7%BD%AE%E8%BF%99%E4%B8%AA%E6%89%8D%E4%BB%A3%E8%A1%A8%E4%BA%8B%E5%8A%A1%E7%94%9F%E6%95%88"><span class="toc-number">11.0.1.</span> <span class="toc-text">配置这个才代表事务生效</span></a></li></ol></li></ol></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>Recent Post</span></div><div class="aside-list"><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2023/03/28/HTTP-1-1%E3%80%81HTTP-2%E3%80%81HTTP-3-%E6%BC%94%E5%8F%98/" title="HTTP/1.1、HTTP/2、HTTP/3 演变">HTTP/1.1、HTTP/2、HTTP/3 演变</a><time datetime="2023-03-28T15:30:00.000Z" title="Created 2023-03-28 23:30:00">2023-03-28</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2023/03/24/HTTPS-%E7%9A%84%E5%BA%94%E7%94%A8%E6%95%B0%E6%8D%AE%E6%98%AF%E5%A6%82%E4%BD%95%E4%BF%9D%E8%AF%81%E5%AE%8C%E6%95%B4%E6%80%A7%E7%9A%84%EF%BC%9F/" title="HTTPS 的应用数据是如何保证完整性的？">HTTPS 的应用数据是如何保证完整性的？</a><time datetime="2023-03-24T09:25:00.000Z" title="Created 2023-03-24 17:25:00">2023-03-24</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2023/03/24/HTTPS-%E6%98%AF%E5%A6%82%E4%BD%95%E5%BB%BA%E7%AB%8B%E8%BF%9E%E6%8E%A5%E7%9A%84%EF%BC%9F/" title="HTTPS 是如何建立连接的？">HTTPS 是如何建立连接的？</a><time datetime="2023-03-24T09:25:00.000Z" title="Created 2023-03-24 17:25:00">2023-03-24</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2023/03/24/HTTPS-%E4%B8%80%E5%AE%9A%E5%AE%89%E5%85%A8%E5%8F%AF%E9%9D%A0%E5%90%97%EF%BC%9F/" title="HTTPS 一定安全可靠吗？">HTTPS 一定安全可靠吗？</a><time datetime="2023-03-24T09:24:00.000Z" title="Created 2023-03-24 17:24:00">2023-03-24</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2023/03/23/%E5%AE%9E%E6%88%98/" title="实战">实战</a><time datetime="2023-03-23T13:52:00.000Z" title="Created 2023-03-23 21:52:00">2023-03-23</time></div></div></div></div></div></div></main><footer id="footer" style="background-image: url('https://img.lovetao.top/img/202303152113310.jpg')"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2023 By 戴涛</div><div class="framework-info"><span>Framework </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>Theme </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="Read Mode"><i class="fas fa-book-open"></i></button><button id="darkmode" type="button" title="Switch Between Light And Dark Mode"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="Toggle between single-column and double-column"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="Setting"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="Table Of Contents"><i class="fas fa-list-ul"></i></button><a id="to_comment" href="#post-comment" title="Scroll To Comments"><i class="fas fa-comments"></i></a><button id="go-up" type="button" title="Back To Top"><span class="scroll-percent"></span><i class="fas fa-arrow-up"></i></button></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.umd.min.js"></script><div class="js-pjax"><script>function loadValine () {
  function initValine () {
    const valine = new Valine(Object.assign({
      el: '#vcomment',
      appId: 'cEUNK0k7aOSrnE93yOEHT9io-gzGzoHsz',
      appKey: '3oME0qpmzHlf1QmZiMY9i8rs',
      avatar: 'declan',
      serverURLs: '',
      emojiMaps: "",
      path: window.location.pathname,
      visitor: false
    }, null))
  }

  if (typeof Valine === 'function') initValine() 
  else getScript('https://cdn.jsdelivr.net/npm/valine/dist/Valine.min.js').then(initValine)
}

if ('Valine' === 'Valine' || !false) {
  if (false) btf.loadComment(document.getElementById('vcomment'),loadValine)
  else setTimeout(loadValine, 0)
} else {
  function loadOtherComment () {
    loadValine()
  }
}</script></div><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div></body></html>